<template>
  <!-- 全局加载提示 -->
  <div v-if="loading" class="loading-overlay">
    <div class="loading-content">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>数据加载中...</span>
    </div>
  </div>

  <div class="layer-container" :class="{ collapsed: isCollapsed }">
    <div class="tree-scroll-container">
      <div class="tree-wrapper">
        <el-tree
          :data="treeData"
          :props="propsData"
          ref="treeRef"
          node-key="id"
          default-expand-all
          show-checkbox
          @check-change="handleCheckChange"
          :disabled="loading"
        >
        </el-tree>
      </div>
    </div>

    <button class="toggle-button" @click="isCollapsed = !isCollapsed" :disabled="loading">
      {{ isCollapsed ? "»" : "«" }}
    </button>
  </div>
  <div>
    <el-button
      @click="zoomIn"
      @mousedown="zoomInMouseDown"
      @mouseup="myMouseUp"
      style="
        position: absolute;
        z-index: 9999;
        left: 17.6%;
        top: 220px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      :disabled="loading"
      >+</el-button
    >
    <el-button
      @click="check3D"
      style="
        position: absolute;
        z-index: 9999;
        left: 16.9%;
        top: 250px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      :disabled="loading"
      >{{ checkLabel }}</el-button
    >
    <el-button
      @click="zoomOut"
      @mousedown="zoomOutMouseDown"
      @mouseup="myMouseUp"
      style="
        position: absolute;
        z-index: 9999;
        left: 16.9%;
        top: 280px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      :disabled="loading"
      >-</el-button
    ><el-button
      @click="zoomToOriginal"
      style="
        position: absolute;
        z-index: 9999;
        left: 16.9%;
        top: 310px;
        background-color: #1e3f5b;
        color: #fff;
        height: 30px;
        width: 20px;
      "
      :disabled="loading"
      >复位</el-button
    >
  </div>
  <div v-if="windData" class="current-data-display">
    <h4>海流信息</h4>
    <p>经度: {{ windData.lon }}° E</p>
    <p>纬度: {{ windData.lat }}° N</p>
    <h5>插值数据</h5>
    <p>流速: {{ windData.interpolated.speed }} m/s</p>
    <p>U 分量: {{ windData.interpolated.u }} m/s</p>
    <p>V 分量: {{ windData.interpolated.v }} m/s</p>
    <h5>原始数据</h5>
    <p>流速: {{ windData.original.speed }} m/s</p>
    <p>U 分量: {{ windData.original.u }} m/s</p>
    <p>V 分量: {{ windData.original.v }} m/s</p>
  </div>

  <div v-if="templatureOrSalt" class="wind-data-display">
    <p>经度: {{ templatureOrSalt.lon }}° E</p>
    <p>纬度: {{ templatureOrSalt.lat }}° N</p>
    <p>{{ layerName }}: {{ templatureOrSalt.value }}{{ dataUnit }}</p>
  </div>
  <Colorbar
    v-show="colorbarShow"
    :min="colorMin"
    :max="colorMax"
    :colors="colors"
    :labelCount="labelCount"
  />
</template>

<script setup>
import { ref, watch, onMounted, nextTick, onBeforeUnmount } from "vue";
import { format } from "date-fns";
import * as Cesium from "cesium";
import eventBus from "@/utils/eventBus";
import { useEddyStore } from "@/stores/eddyStore";
import { useYuecengStore } from "@/stores/yuecengStore";
import { useCurrentStore } from "@/stores/currentStore";
import { useNeiboStore } from "@/stores/neiboStore";
import Colorbar from "./ColorBar.vue";
// import eddiesData from "@/assets/20220101eddies.json";
// import neibodata from "@/assets/neibooutput.json";
// import yuecengData from "@/assets/yueceng.json";
import sampleStationsData from "@/assets/chaozhan.json";
// import sla from "@/assets/20220101sla.json";
import { useFengmianStore } from "@/stores/fengmianStore";
import { useData2DStore } from "@/stores/data2DStore";
import { useStationsStore } from "@/stores/stationsStore";
import { ElMessage } from "element-plus";
import { Loading } from "@element-plus/icons-vue";
import {
  getChaoData,
  getNeiBoBeiJingData,
  getNeiBoData,
  getXuanWoData,
  getXuanWoSLAData,
  getYueCengData,
  getFengMianData,
  getFengmianLunKuoData,
  getYanDuData,
  getYanDuHighData,
  getWenDuData,
  getWenDuHighData,
  getHaiLiuData,
  getQianBiaoData,
} from "@/api";
const stationsStore = useStationsStore();
const data2DStore = useData2DStore();
const fengmianStore = useFengmianStore();
const currentStore = useCurrentStore();
const yuecengStore = useYuecengStore();
const eddyStore = useEddyStore();
const neiboStore = useNeiboStore();

const viewerHandle = ref({});
const currentLayer = ref({});
const colorbarShow = ref(false);
let checkLabel = ref("2D");
const isPressing = ref(false);
let interval = null;
const windData = ref(null);
const templatureOrSalt = ref(null);
const layerName = ref("");
const dataUnit = ref("");
const colorMax = ref(1.23);
const colorMin = ref(0);
const labelCount = ref(10);
const colors = ref([
  "#d61600",
  "#ce2d02",
  "#c64404",
  "#be5b06",
  "#b67208",
  "#ae890a",
  "#a6a00c",
  "#9eb70e",
  "#96ce10",
  "#8ee80e",
]);
const loading = ref(false);
let currentData = ref(null);
const props = defineProps({
  viewerHandle: {
    type: Object,
    required: true,
  },
});

const isCollapsed = ref(false);
const propsData = {
  label: "name",
  children: "children",
};
const treeRef = ref(null);
const isInternalCheck = ref(false);
const currentDataPromise = ref(null); // 存储海流数据的Promise
const pendingVectorLoad = ref(false); // 标记是否有矢量图层在等待加载

// 定义互斥组
const exclusiveGroups = {
  gradientGroup: [9, 13, 15, 19, 20, 21, 22, 23],
  eddyYuecengGroup: [5, 6],
};

const treeData = ref([
  {
    name: "温度",
    id: 1,
    disabled: true,
    children: [{ name: "温度图层", id: 19 }],
  },
  {
    name: "盐度",
    id: 2,
    disabled: true,
    children: [{ name: "盐度图层", id: 21 }],
  },
  {
    name: "海流",
    id: 3,
    // disabled: true,
    children: [
      { name: "海流强度图层", id: 9 },
      { name: "海流矢量图层", id: 10 },
    ],
  },
  {
    name: "潮位",
    id: 4,
    children: [
      { name: "潮位预报", id: 23 },
      { name: "重要潮站", id: 24 },
    ],
  },
  {
    name: "中尺度涡",
    id: 5,
    children: [
      { name: "气旋涡", id: 11, type: "cold" },
      { name: "反气旋涡", id: 12, type: "warm" },
      { name: "海表面高度", id: 13 },
    ],
  },
  {
    name: "跃层",
    id: 6,
    children: [
      { name: "Argo浮标", id: 17 },
      { name: "潜标", id: 18 },
    ],
  },
  {
    name: "锋面",
    id: 7,
    children: [
      { name: "锋中心线", id: 14 },
      { name: "锋区范围", id: 16 },
      { name: "锋面强度", id: 15 },
    ],
  },
  {
    name: "内波",
    disabled: true,
    id: 8,
    children: [
      { name: "波峰线", id: 25 },
      { name: "波向", id: 26 },
    ],
  },
]);
// 查找树节点
const findNodeById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
};
let allTime = ref("2025-03-23");
// 处理复选框变化
const handleCheckChange = async (data, checked, isInternal = false) => {
  if (isInternal) return;
  // 获取当前选中的keys
  const checkedKeys = treeRef.value.getCheckedKeys(false);
  // console.log("checkedKeys", checkedKeys);
  // 触发事件通知RightTools组件
  eventBus.$emit("layer-check-change", checkedKeys);
  // 获取当前时间，默认为"2025-03-23"
  const currentTime = format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss") || "2025-03-19";
  if (!checked) {
    // eventBus.setCurrentLayer("");
    switch (data.name) {
      case "温度":
      case "盐度":
      case "海流强度图层":
        currentData.value = null;
      case "锋面强度":
      case "海表面高度":
      case "潮位预报":
        templatureOrSalt.value = null;
        data2DStore.hide();
        colorbarShow.value = false;
        break;
      case "重要潮站":
        stationsStore.setStationsData(sampleStationsData);
        stationsStore.toggleVisibility(false);
        break;
      case "气旋涡":
        eddyStore.toggleEddyVisibility(false, "cold");
        break;
      case "反气旋涡":
        eddyStore.toggleEddyVisibility(false, "warm");
        break;
      case "Argo浮标":
        yuecengStore.toggleVisibility("fubiao");
        break;
      case "潜标":
        yuecengStore.toggleVisibility("qianbiao");
        break;
      case "海流矢量图层":
        windData.value = null;
        currentData.value = null;
        currentStore.toggleCurrentVisibility();
        break;
      case "锋中心线":
        fengmianStore.toggleVisibility("frontSegments");
        break;
      case "锋区范围":
        fengmianStore.toggleVisibility("boundaryPolygons");
        break;
      case "波峰线":
        neiboStore.toggleNeiboVisibility();
        break;
      case "波向":
        neiboStore.toggleArrowsVisibility(false);
        break;
    }
    return;
  }

  isInternalCheck.value = true;
  const exclusiveGroup = getExclusiveGroup(data.id);
  if (exclusiveGroup) {
    const checkedKeys = treeRef.value.getCheckedKeys(false);
    checkedKeys.forEach((key) => {
      if (exclusiveGroup.includes(key) && key !== data.id) {
        treeRef.value.setChecked(key, false, false);
      }
    });
  }
  isInternalCheck.value = false;
  loading.value = true;
  try {
    switch (data.name) {
      case "温度图层":
        eventBus.setCurrentLayer("temperature");
        await loadTemperatureData();
        break;
      case "盐度图层":
        eventBus.setCurrentLayer("salinity");
        await loadSaltData();
        break;
      case "海流强度图层":
        await loadCurrentIntensityData();
        eventBus.setCurrentLayer("current");
        break;
      case "潮位预报":
        eventBus.setCurrentLayer("chao");
        await loadTideData(currentTime);
        break;
      case "重要潮站":
        eventBus.setCurrentLayer("chao");
        stationsStore.setStationsData(sampleStationsData);
        stationsStore.setTime(currentTime);
        stationsStore.toggleVisibility(true);
        break;
      case "海表面高度":
        let slaData = await getXuanWoSLAData({ ctime: currentTime });
        await loadSlaData(slaData[0].data);
        break;
      case "锋面强度":
        await loadFrontIntensityData(currentTime);
        break;
      case "气旋涡":
        eventBus.setCurrentLayer("eddy");
        let eddiesDataCold = await getXuanWoData({ ctime: currentTime });
        eddyStore.setEddiesData(eddiesDataCold[0].data, "cold");
        eddyStore.toggleEddyVisibility(true, "cold");
        break;
      case "反气旋涡":
        eventBus.setCurrentLayer("eddy");
        let eddiesDataWarm = await getXuanWoData({ ctime: currentTime });
        eddyStore.setEddiesData(eddiesDataWarm[0].data, "warm");
        eddyStore.toggleEddyVisibility(true, "warm");
        break;
      case "Argo浮标":
        eventBus.setCurrentLayer("yueceng");
        // 转换为当月第一天 (格式: YYYY-MM-01T00:00:00)
        const firstDayOfMonthFubiao = currentTime.substring(0, 8) + "01";
        let yuecengDatafubiao = await getYueCengData({
          ctime: firstDayOfMonthFubiao,
        });
        if (!yuecengDatafubiao || yuecengDatafubiao.length === 0) {
          yuecengStore.toggleVisibility("fubiao");
          throw new Error(`当前时间点 ${currentTime} 没有跃层数据`);
        }
        yuecengDatafubiao = transformData(yuecengDatafubiao[0].data);
        yuecengStore.setYuecengData({
          type: "fubiao",
          data: yuecengDatafubiao,
        });
        yuecengStore.toggleVisibility("fubiao");

        break;
      case "潜标":
        eventBus.setCurrentLayer("yueceng");
        // 转换为当月第一天 (格式: YYYY-MM-01T00:00:00)
        // const firstDayOfMonthQianbiao = currentTime.substring(0, 8) + "01";
        let yuecengDataqianbiao = await getQianBiaoData({
          ctime: currentTime,
        });
        if (!yuecengDataqianbiao || yuecengDataqianbiao.length === 0) {
          yuecengStore.toggleVisibility("qianbiao");
          throw new Error(`当前时间点 ${currentTime} 没有潜标数据`);
        }
        yuecengDataqianbiao = transformData(yuecengDataqianbiao[0].data);
        yuecengStore.setYuecengData({
          type: "qianbiao",
          data: yuecengDataqianbiao,
        });
        yuecengStore.toggleVisibility("qianbiao");
        break;
      case "锋中心线":
        await loadFrontCenterData(currentTime);
        break;
      case "锋区范围":
        await loadFrontAreaData(currentTime);
        break;
      case "波峰线":
        eventBus.setCurrentLayer("neibo");
        let neibodata = await getNeiBoData({ ctime: currentTime });
        let sla = await getNeiBoBeiJingData({ ctime: currentTime });
        if (!neibodata || neibodata.length === 0) {
          throw new Error(`当前时间点 ${currentTime} 没有内波数据`);
        }
        if (!sla || sla.length === 0) {
          neiboStore.setslaData(null);
        } else {
          neiboStore.setslaData(sla[0].data.data[0]);
        }
        neiboStore.setToday(currentTime);
        neiboStore.setNeiboData(neibodata[0]);
        neiboStore.toggleNeiboVisibility(true);
        break;
      case "波向":
        eventBus.setCurrentLayer("neibo");
        neiboStore.toggleArrowsVisibility(true);
        break;
      case "海流矢量图层":
        if (currentDataPromise.value) {
          pendingVectorLoad.value = true;
          await currentDataPromise.value;
          pendingVectorLoad.value = false;
        }
        eventBus.setCurrentLayer("current");
        await loadCurrentVectorData();
        break;
    }
  } catch (error) {
    console.error("加载图层失败:", error);
    ElMessage.error({
      message: `加载${data.name}失败: ${error.message}`,
      customClass: "center-message",
      showClose: true,
    });
    treeRef.value.setChecked(data.id, false, false);
  } finally {
    loading.value = false;
  }
};
function transformData(originalData) {
  return originalData.data.map((item, index) => ({
    ...item,
    press: originalData.press[index] || [],
    salinity: originalData.salnity[index] || [],
    temperature: originalData.tempereture[index] || [],
  }));
}
// 各个图层加载函数
const loadTemperatureData = async (time, depth = 1) => {
  const temperatureData = await getWenDuData({
    ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
    high: eventBus.currentDepth,
  });

  if (!temperatureData || temperatureData.length === 0) {
    throw new Error(
      `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有温度数据`
    );
  }
  await loadLayerData({
    data: temperatureData[0].high.data,
    header: temperatureData[0].high.header,
    type: "温度",
    isGradient: true,
    dataUnit: "℃",
    id: 19,
    min: getSlaMinMax(temperatureData[0].high.data).min,
    max: getSlaMinMax(temperatureData[0].high.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadTemperatureDepthData = async (time, depth = 1) => {
  const temperaturehighData = await getWenDuHighData({
    ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
    high: eventBus.currentDepth,
  });
  if (!temperaturehighData || temperaturehighData.length === 0) {
    throw new Error(
      `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有温度深度数据`
    );
  }
  await loadLayerData({
    data: temperaturehighData[0].high.data,
    header: temperaturehighData[0].high.header,
    type: "深度",
    dataUnit: "m",
    id: 20,
    min: getSlaMinMax(temperaturehighData[0].high.data).min,
    max: getSlaMinMax(temperaturehighData[0].high.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadSaltData = async (time, depth = 1) => {
  const saltData = await getYanDuData({
    ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
    high: eventBus.currentDepth,
  });
  if (!saltData || saltData.length === 0) {
    throw new Error(
      `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有盐度数据`
    );
  }
  await loadLayerData({
    data: saltData[0].data.data,
    header: saltData[0].data.header,
    type: "盐度",
    isGradient: true,
    id: 21,
    min: 30,
    max: getSlaMinMax(saltData[0].data.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadSaltDepthData = async (time, depth = 1) => {
  const salthighData = await getYanDuHighData({
    ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
    high: eventBus.currentDepth,
  });
  if (!salthighData || salthighData.length === 0) {
    throw new Error(
      `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有盐度深度数据`
    );
  }
  await loadLayerData({
    data: salthighData[0].high.data,
    header: salthighData[0].high.header,
    type: "深度",
    dataUnit: "m",
    id: 22,
    // colors: ["#0D4D4B", "#35A69C", "#64E9EE", "#FFCC00"],
    min: getSlaMinMax(salthighData[0].high.data).min,
    max: getSlaMinMax(salthighData[0].high.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadCurrentIntensityData = async () => {
  // 如果已经有请求在进行，直接等待它
  if (!currentDataPromise.value) {
    currentDataPromise.value = getHaiLiuData({
      ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
      high: eventBus.currentDepth,
    }).finally(() => {
      currentDataPromise.value = null;
    });
  }

  try {
    currentData.value = await currentDataPromise.value;

    if (!currentData.value || !currentData.value.data) {
      throw new Error(
        `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有海流数据`
      );
    }

    const newdata = processCurrentData(currentData.value.data);
    await loadLayerData({
      data: newdata.data,
      header: newdata.header,
      type: "海流强度",
      dataUnit: "m/s",
      id: 9,
      isGradient: true,
      min: getSlaMinMax(newdata.data).min,
      max: getSlaMinMax(newdata.data).max,
    });
    window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);

    // 如果有矢量图层在等待，立即加载
    if (pendingVectorLoad.value) {
      await loadCurrentVectorData();
    }
  } catch (error) {
    currentDataPromise.value = null;
    throw error;
  }
};

const loadTideData = async (time) => {
  const chaodata = await getChaoData({ ctime: time });
  if (!chaodata || chaodata.length === 0) {
    throw new Error(`当前时间点 ${time} 没有潮位数据`);
  }
  await loadLayerData({
    data: chaodata[0].data.data,
    header: chaodata[0].data.header,
    isGradient: false,
    type: "潮位",
    dataUnit: "m",
    id: 23,
    min: getSlaMinMax(chaodata[0].data.data).min,
    max: getSlaMinMax(chaodata[0].data.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadSlaData = async (sla) => {
  let res = getSlaMinMax(sla.data);
  await loadLayerData({
    data: sla.data,
    header: sla.header,
    isGradient: false,
    type: "海表面高度",
    dataUnit: "m",
    id: 13,
    min: res.min,
    max: res.max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadFrontIntensityData = async (time) => {
  const resfengmianNewData = await getFengMianData({ ctime: time });
  if (!resfengmianNewData || resfengmianNewData.length === 0) {
    throw new Error(`当前时间点 ${time} 没有锋面强度数据`);
  }
  await loadLayerData({
    data: resfengmianNewData[0].data.data,
    header: resfengmianNewData[0].data.header,
    type: "锋面强度",
    isGradient: true,
    dataUnit: "℃/km",
    id: 15,
    colors: ["#4BC2BF", "#64E9EE", "#B2D882", "#FFCC00", "#FFAE00", "#FF9900", "#FF0000"],
    min: getSlaMinMax(resfengmianNewData[0].data.data).min,
    max: getSlaMinMax(resfengmianNewData[0].data.data).max,
  });
  window.addEventListener("templatureOrSalt", handleTemperatureOrSalt);
};

const loadFrontCenterData = async (time) => {
  eventBus.setCurrentLayer("fengmian");
  const fengmianzhongxin = await getFengmianLunKuoData({ ctime: time });
  if (!fengmianzhongxin || fengmianzhongxin.length === 0) {
    throw new Error(`当前时间点 ${time} 没有锋中心线数据`);
  }
  fengmianStore.setFengmianData(fengmianzhongxin[0].data);
  fengmianStore.toggleVisibility("frontSegments");
};

const loadFrontAreaData = async (time) => {
  eventBus.setCurrentLayer("fengmian");
  const fengmianlunkuo = await getFengmianLunKuoData({ ctime: time });
  if (!fengmianlunkuo || fengmianlunkuo.length === 0) {
    throw new Error(`当前时间点 ${time} 没有锋区范围数据`);
  }
  fengmianStore.setFengmianData(fengmianlunkuo[0].data);
  fengmianStore.toggleVisibility("boundaryPolygons");
};

const loadCurrentVectorData = async (time, depth = 1) => {
  if (currentData.value == null) {
    currentData.value = await getHaiLiuData({
      ctime: format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss"),
      high: eventBus.currentDepth,
    });
  }
  if (!currentData.value || !currentData.value.data) {
    throw new Error(
      `当前时间点 ${format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss")} 没有海流矢量数据`
    );
  }
  currentStore.setWindData(currentData.value.data);
  currentStore.setinterpolatedColors(["#ffffff"]);
  currentStore.toggleCurrentVisibility(true);
  window.addEventListener("wind-data", handleWindData);
};
const getExclusiveGroup = (id) => {
  for (const [_, ids] of Object.entries(exclusiveGroups)) {
    if (ids.includes(id)) return ids;
  }
  return null;
};

const loadLayerData = async (config) => {
  try {
    // 验证数据是否可序列化
    const testClone = structuredClone(config.data);
  } catch (e) {
    console.error("数据不可序列化:", config.data);
    throw new Error("数据格式错误，无法加载图层");
  }
  if (data2DStore.isVisible) {
    data2DStore.hide();
    await nextTick();
  }
  const layerId = config.id; // 需要在调用时传入图层ID
  // 从eventBus获取颜色配置
  const configcolors = eventBus.getLayerColors(layerId);
  data2DStore.setData(Array.from(config.data));
  data2DStore.setHeader(config.header);
  data2DStore.setIsGradient(config.isGradient);
  data2DStore.setColors(configcolors);
  data2DStore.minDataValue = config.min;
  data2DStore.maxDataValue = config.max;

  layerName.value = config.type;
  dataUnit.value = config.dataUnit;
  colorMin.value = config.min;
  colorMax.value = config.max;
  colors.value = configcolors;
  labelCount.value = configcolors.length;

  await data2DStore.show();
  colorbarShow.value = true;
};

const getSlaMinMax = (slaData) => {
  // 过滤掉 null 值并转换为有效数字
  const validNumbers = slaData
    .filter((item) => item !== null)
    .map(Number)
    .filter(Number.isFinite);

  if (validNumbers.length === 0) {
    return { min: NaN, max: NaN };
  }

  // 计算最小值和最大值
  const min = Math.min(...validNumbers);
  const max = Math.max(...validNumbers);

  // 截取到小数点后六位
  const truncateToSixDecimals = (num) => {
    return Math.floor(num * 1e8) / 1e8;
  };

  return {
    min: truncateToSixDecimals(min),
    max: truncateToSixDecimals(max),
  };
};

const processCurrentData = (originalArray) => {
  const [uData, vData] = originalArray.filter((item) =>
    [3, 2].includes(item.header.parameterNumber)
  );

  const rawIntensity = uData.data.map((u, index) => {
    const v = vData.data[index];
    return isNaN(u) || isNaN(v) ? "NaN" : Math.hypot(u, v);
  });

  const processedData = rawIntensity.map((value) => (value === 0 ? null : value));

  const validData = processedData.filter((v) => typeof v === "number" && v !== null);

  return {
    header: uData.header,
    data: processedData,
    max: validData.length ? Math.max(...validData) : null,
    min: validData.length ? Math.min(...validData) : null,
  };
};

// 其他原有方法保持不变
watch(
  () => props.viewerHandle,
  (newValue) => {
    viewerHandle.value = newValue;
  }
);

onMounted(() => {
  viewerHandle.value = props.viewerHandle;
  currentLayer.value = props.currentLayer;
  // 时间变化 - 影响所有选中图层
  eventBus.$on("time-change", handleTimeChange);

  // 深度变化 - 只影响温盐流图层
  eventBus.$on("depth-change", handleDepthChange);
});

onBeforeUnmount(() => {
  eventBus.$off("time-change", handleTimeChange);
  eventBus.$off("depth-change", handleDepthChange);
});
// 时间变化处理
const handleTimeChange = async (formattedDate) => {
  allTime.value = formattedDate;
  const checkedKeys = treeRef.value?.getCheckedKeys(false) || [];
  if (checkedKeys.length === 0) return;

  // 重置海流数据状态
  currentDataPromise.value = null;
  currentData.value = null;
  pendingVectorLoad.value = false;

  // 重新加载所有选中图层
  for (const layerId of checkedKeys) {
    await reloadLayer(layerId);
  }
};

// 深度变化处理
const handleDepthChange = async (depth) => {
  const checkedKeys = treeRef.value?.getCheckedKeys(false) || [];
  if (checkedKeys.length === 0) return;

  // 只重新加载温盐流相关图层
  for (const layerId of checkedKeys) {
    if (eventBus.depthSensitiveLayers.includes(layerId)) {
      await reloadLayer(layerId);
    }
  }
};

// 通用图层重新加载方法
const reloadLayer = async (layerId) => {
  const node = findNodeById(treeData.value, layerId);
  if (!node) return;

  try {
    treeRef.value.setChecked(layerId, false, false);
    await nextTick();
    treeRef.value.setChecked(layerId, true, false);
  } catch (error) {
    console.error(`重新加载 ${node.name} 失败:`, error);
    ElMessage.error(`${node.name} 更新失败`);
  }
};
const handleWindData = (event) => {
  windData.value = event.detail;
};

const handleTemperatureOrSalt = (event) => {
  templatureOrSalt.value = event.detail;
};

const check3D = () => {
  if (viewerHandle.value.scene.mode === Cesium.SceneMode.SCENE3D) {
    viewerHandle.value.scene.mode = Cesium.SceneMode.SCENE2D;
    checkLabel.value = "3D";
  } else {
    viewerHandle.value.scene.mode = Cesium.SceneMode.SCENE3D;
    checkLabel.value = "2D";
  }
};

const zoomIn = () => {
  let position = viewerHandle.value.camera.position;
  let cameraHeight =
    viewerHandle.value.scene.globe.ellipsoid.cartesianToCartographic(position).height;
  let moveRate = cameraHeight / 30.0;
  viewerHandle.value.camera.moveForward(moveRate);
};

const zoomOut = () => {
  let position = viewerHandle.value.camera.position;
  let cameraHeight =
    viewerHandle.value.scene.globe.ellipsoid.cartesianToCartographic(position).height;
  let moveRate = cameraHeight / 30.0;
  viewerHandle.value.camera.moveBackward(moveRate);
};

const zoomInMouseDown = () => {
  isPressing.value = true;
  interval = setInterval(() => zoomIn(), 30);
};

const zoomOutMouseDown = () => {
  isPressing.value = true;
  interval = setInterval(() => zoomOut(), 30);
};

const myMouseUp = () => {
  isPressing.value = false;
  clearInterval(interval);
};

const zoomToOriginal = () => {
  viewerHandle.value.camera.setView({
    destination: {
      x: -3558397.3075464107,
      y: 7300150.323537398,
      z: 2041719.4055434903,
    },
    orientation: {
      heading: 6.27669114823209,
      pitch: -1.248789382616426,
      roll: 6.283120764297309,
    },
  });
};
</script>

<style scoped>
/* 加载遮罩样式 - 透明底色白色文字 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  background-color: transparent;
  padding: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  font-size: 18px;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}

.loading-content .el-icon {
  color: white;
  font-size: 24px;
  animation: rotating 2s linear infinite;
}

/* 主容器样式 */
.layer-container {
  width: 15%;
  height: 95%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
  background-color: rgba(24, 44, 70, 0.8);
  border-radius: 10px 10px 10px 0;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
}

.tree-scroll-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-right: 2px;
  display: flex;
  flex-direction: column;
}

.tree-wrapper {
  margin: auto 0;
  width: 100%;
}

/* 暗色风格滚动条 */
.tree-scroll-container::-webkit-scrollbar {
  width: 8px;
}
.tree-scroll-container::-webkit-scrollbar-thumb {
  background-color: rgba(64, 158, 255, 0.6);
  border-radius: 4px;
}
.tree-scroll-container::-webkit-scrollbar-track {
  background-color: rgba(16, 32, 54, 0.4);
  border-radius: 4px;
}

/* 树形控件样式 - 加大字体部分 */
.layer-container .el-tree {
  background-color: transparent;
  color: #fff;
  width: 100%;
  font-size: 16px;
}

.layer-container :deep(.el-tree-node.is-root > .el-tree-node__content .el-tree-node__label) {
  font-size: 18px;
  font-weight: 500;
}

.layer-container :deep(.el-tree-node__content .el-tree-node__label) {
  font-size: 16px;
}

.layer-container :deep(.el-checkbox__inner) {
  width: 16px;
  height: 16px;
}
.layer-container :deep(.el-checkbox__inner::after) {
  height: 8px;
  left: 5px;
}

.layer-container :deep(.el-tree-node__content) {
  height: 32px;
  line-height: 32px;
  padding: 0 8px;
}

/* 收缩按钮 */
.toggle-button {
  width: 12px;
  padding: 15px 0;
  position: absolute;
  right: -12px;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 1000;
}

/* 解决点击白屏问题 */
.layer-container :deep(.el-tree-node:focus > .el-tree-node__content),
.layer-container :deep(.el-tree-node__content:focus) {
  background-color: transparent !important;
}

/* 悬停效果 */
.layer-container :deep(.el-tree-node__content:hover) {
  background-color: rgba(56, 142, 240, 0.4) !important;
}
.layer-container :deep(.el-tree-node__content:hover .el-tree-node__label) {
  color: #fff !important;
}

/* 选中状态 */
.layer-container :deep(.el-tree-node.is-checked > .el-tree-node__content) {
  background-color: rgba(64, 158, 255, 0.25) !important;
}

/* 强制保持原始收缩宽度 */
.collapsed {
  transform: translateX(-100%);
  width: 0 !important;
  padding-left: 0;
}

.wind-data-display,
.current-data-display {
  position: absolute;
  background: rgba(255, 255, 255, 0.9);
  padding: 6px 10px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  font-size: 13px;
  line-height: 1.3;
}

/* 保持原有位置不变 */
.wind-data-display {
  bottom: 320px;
  right: 17%;
}

.current-data-display {
  bottom: 425px;
  right: 17%;
}

/* 调整内部元素间距 */
.wind-data-display p,
.current-data-display p {
  margin: 4px 0;
}

.wind-data-display h5,
.current-data-display h5 {
  margin: 6px 0 4px 0;
  font-size: 13px;
}

.wind-data-display h4,
.current-data-display h4 {
  margin: 0 0 6px 0;
  font-size: 14px;
}

/* 旋转动画 */
@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
<style>
/* 全局样式 - 不受scoped限制 */
.el-message.center-message {
  top: 50% !important;
  left: 35% !important;
  transform: translateY(-50%) !important;
}
</style>
